package com.hcnow.common.config.webSocket

import org.springframework.messaging.Message
import org.springframework.messaging.support.ChannelInterceptorAdapter
import java.util.LinkedList
import org.springframework.messaging.simp.SimpMessageHeaderAccessor
import org.springframework.messaging.simp.stomp.StompCommand
import org.springframework.messaging.simp.stomp.StompHeaderAccessor
import org.springframework.messaging.support.MessageHeaderAccessor
import org.springframework.messaging.MessageChannel

class WebSocketUserInterceptor: ChannelInterceptorAdapter(){
    override fun preSend(message:Message<*>, channel:MessageChannel ): Message<*> {
        val accessor:StompHeaderAccessor  = MessageHeaderAccessor.getAccessor(message,StompHeaderAccessor::class.java);
        if (StompCommand.CONNECT == accessor.command) {
            val raw = message.headers[SimpMessageHeaderAccessor.NATIVE_HEADERS]
            if (raw is Map<*, *>) {
                val userIds = raw["userId"]
                val appIds = raw["appId"]
                val projectIds = raw["projectId"]
                if (userIds is LinkedList<*> && appIds is LinkedList<*> && projectIds is LinkedList<*>) {
                    //设置当前访问器的认证用户
                    accessor.user = WebSocketUser(appIds[0].toString(), projectIds[0].toString(), userIds[0].toString())
                }
            }
        }
        return message
    }

}